package com.softeem.servlet;

import com.softeem.bean.User;
import com.softeem.service.UserService;
import com.softeem.service.impl.UserServiceImpl;
import com.softeem.utils.BaseServlet;
import com.softeem.utils.CookieUtils;
import com.softeem.utils.WebUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(value="/UserServlet")
public class UserServlet extends BaseServlet {

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();//销毁当前session对象
        //销毁session之后.一定要记的把cookie删除掉.否则点到登录页.又会自动登录了
        Cookie usernameCookie = new Cookie("username" , "");
        usernameCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");
        usernameCookie.setMaxAge(0);//设置0就表式立即删除
        resp.addCookie(usernameCookie);//立即删除掉该Cookie

        Cookie passwordCookie = new Cookie("password" , "");
        passwordCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");
        passwordCookie.setMaxAge(0);
        resp.addCookie(passwordCookie);

        resp.sendRedirect(req.getContextPath()+"/pages/user/login.jsp");
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        /*String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User(null , username ,password, null);*/
        User user = new User();
        WebUtils.copyParamToBean( req.getParameterMap() ,user);
        UserService userService = new UserServiceImpl();
        User login = userService.login(user);
        //判断login是不是一个null对象
        if( login  == null ){
            //如果是null对象表示用户名密码输入错误
            //System.out.println("用户名密码输入错误");
            HttpSession session = req.getSession();
            session.setAttribute("msg" , "账号名或登录密码不正确");
            session.setAttribute("username" , user.getUsername());
            session.setAttribute("password" , user.getPassword());

            Cookie usernameCookie = new Cookie("username" , "");
                usernameCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");
                usernameCookie.setMaxAge(0);//设置0就表式立即删除
                resp.addCookie(usernameCookie);//立即删除掉该Cookie

            Cookie passwordCookie = new Cookie("password" , "");
                passwordCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");
                passwordCookie.setMaxAge(0);
                resp.addCookie(passwordCookie);

            resp.sendRedirect(req.getContextPath()+"/pages/user/login.jsp");
            //错误的话.就跳回到login.html网页
            //req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else {
            //如果来成功执行处.我们来把用户名与密码保存到cookie中
            Cookie usernameCookie = new Cookie("username" , login.getUsername());
            usernameCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");//只有在访问login.jsp时.才会发送cookie
            usernameCookie.setMaxAge(60*60*24*7);//保存7天
            Cookie passwordCookie = new Cookie("password" , login.getPassword());
            passwordCookie.setPath(req.getContextPath()+"/pages/user/login.jsp");
            passwordCookie.setMaxAge(60*60*24*7);
            resp.addCookie(usernameCookie);
            resp.addCookie(passwordCookie);

            HttpSession session = req.getSession();//使用request对象来获取session
            session.setAttribute("user" , login);
            //否则表示用户名密码输入正确,跳转到登录成功页
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        /*Map<String, String[]> parameterMap = req.getParameterMap();
        for (String key : parameterMap.keySet()) {
            System.out.println( key + " = " + parameterMap.get(key)[0]);
        }

        User user = new User();
        try {
            System.out.println("之前:"+user);
            //创建一个日期转换器
            DateConverter dateConverter = new DateConverter();
            String[] patt = {"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"};
            //设置格式
            dateConverter.setPatterns(patt);
            //注册格式
            ConvertUtils.register(dateConverter, Timestamp.class);
            BeanUtils.populate(user , parameterMap);
            System.out.println("之后:"+user);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }*/
        /*String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");*/
        User user = new User();
        WebUtils.copyParamToBean(req.getParameterMap() , user);

        String code = req.getParameter("code");

        req.setAttribute("username" , user.getUsername());
        req.setAttribute("password" , user.getPassword());
        req.setAttribute("email", user.getEmail());
        //从session会话作用域中获取验证码的值
        String token = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码,因为使用完之后就从session中删除.也是为了解决表单重复提交问题
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //创建用户的业务层对象 :userService
        UserService userService = new UserServiceImpl();
        if (token != null && token.equalsIgnoreCase(code)) {//判断验证码是否正确
            if (userService.existsUsername(user.getUsername())) {
                //返回为true表示此用户名可以使用
                userService.registUser(user);//调用业务层方法保存用户数据
                HttpSession session = req.getSession();
                session.setAttribute("user" , user);
                //跳转到注册成功页
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            } else {
                //否则此用户名已经被占用
                //System.out.println("用户名[" + username + "]已存在!");
                req.setAttribute("msg" , "用户名["+user.getUsername()+"]已存在!");
                //跳回到注册页
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            }
        } else {
            //System.out.println(" 验 证 码 [" + code + "] 错 误 ");
            req.setAttribute("msg" , "验证码错误!");
            //跳回到注册页
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}

